import React from 'react';
import { Select } from '@teamix/ui';
import { ButtonIcon } from '@alife/devops-ui';
import ListEmpty from 'atComponents/ListEmpty';
import MdEditor from 'components/mdEditor';
import './index.scss';
import Conversation from '../diff/conversation';
import { ENUM } from 'utils/constants';
import utils from 'utils';
import track from 'utils/track';
import intl from '../../../../../../../../../../../locale';

const { pathResource } = window.FORCE;
const { ctrlTxt } = ENUM.getOSKeyMap();

const discussStatuses = [
  {
    value: 'all',
    label: intl.get({
      id: 'code-assets.components.comment.AllComments',
      defaultMessage: '全部评论',
    }),
  },
  {
    value: 'open',
    label: intl.get({
      id: 'code-assets.components.comment.PendingComments',
      defaultMessage: '待解决评论',
    }),
  },
];

export default class CommentList extends React.Component {
  constructor(props) {
    super(props);
    // 不是从overview跳转过来打开的，就默认过滤状态为all
    const { curCommentStatus } = props;
    this.state = {
      isShowWholeCommentMd: false,
      isShowMore: false,
      // 默认显示所有评论
      status: curCommentStatus || 'all',
    };
    this.allCommentList = React.createRef();
  }

  componentDidMount() {
    // 定位,改用监听滚动
    const container = document.querySelector('.comment-list-container');
    const mrHeader = document.querySelector('.mr-detail-content-header');
    const mrHeaderTop = mrHeader ? mrHeader.getBoundingClientRect().top : 51;
    const mrHeaderHeight = mrHeader ? mrHeader.offsetHeight : 0;
    if (container) {
      container.style.top = `${mrHeaderHeight + mrHeaderTop}px`;
    }
    if (document.querySelector('.mr-detail-content-body ')) {
      document.querySelector('.mr-detail-content-body ').classList.add('hideScroll');
    }
  }

  componentWillUnmount() {
    const container = document.querySelector('.comment-list-container');
    if (container) {
      container.scrollTop = 0;
    }
    if (document.querySelector('.mr-detail-content-body ')) {
      document.querySelector('.mr-detail-content-body ').classList.remove('hideScroll');
    }
  }

  showAllCommentArea = () => {
    const { allComments, mrCommentConfig } = this.props;
    const allowComments = utils.allowComments(allComments.length, mrCommentConfig);
    const hasPermission = pathResource.isArchive === 'false' && allowComments;
    if (!hasPermission) {
      return;
    }
    this.setState({
      isShowWholeCommentMd: true,
    });
  };

  // 提交整体评论或者草稿
  onSubmitWhole = (value, is_draft, parent_note_id) => {
    const { codeReviewDetail } = this.props;
    this.props.postInlineComments(
      {
        note: value,
        parent_note_id: parent_note_id || '',
        is_draft: !!is_draft,
      },

      () => {
        this.setState({
          isShowWholeCommentMd: false,
        });
      },
    );

    track({
      action: 'view_comments_panel_overall_post',
      page: 'Repo-MR-changes',
      type: '',
      mr_id: codeReviewDetail.id,
    });
  };

  toggleMore = (e) => {
    e.stopPropagation();
    const { isShowMore } = this.state;
    this.setState({
      isShowMore: !isShowMore,
    });
  };

  componentDidUpdate() {
    const { comment_jump } = this.props;
    // if (hash && hash.file && comment_jump && comment_jump === hash.file) {
    if (comment_jump) {
      // anchor_conversation_2003216
      const mrComment = this.allCommentList.current;
      const fileDom = mrComment.getElementsByClassName(`${comment_jump}_comment_jump_item`)[0];
      mrComment.scrollTop = fileDom && fileDom.offsetTop > 0 ? fileDom.offsetTop - 96 : 0;
      this.props.commentJump(null);
    }
  }

  renderAllComments = () => {
    const { allComments } = this.props;
    const { status } = this.state; // isShowMore,
    // const data = [...allComments, ...drafts];
    // 评论不显示草稿
    const data = [...allComments];

    // 递归形成讨论块：以无parent_note_id的评论作为讨论块的跟节点，其子评论平铺在下面
    const { conversations, openConversations } = utils.comments2Conversations(data);

    let curConversations = [];
    // 过滤
    const isOpen = status === 'open';
    if (isOpen) {
      curConversations = openConversations;
    } else {
      curConversations = conversations;
    }
    // mr 评论优化
    // const conversationsLength = curConversations.length;
    // if (conversationsLength > 8 && !isShowMore) {
    //   curConversations = curConversations.slice(conversationsLength - 8, conversationsLength);
    // }

    const filterEmptyEle = (
      <div className="comment-list-empty">
        <ListEmpty
          image="none"
          content={intl.get({
            id: 'code-assets.components.comment.NoData',
            defaultMessage: '暂无数据',
          })}
          size="small"
          type="card"
          className="no-btns"
        />
      </div>
    );

    // const moreConversationsLength = (isOpen ? openConversations.length : conversations.length) - 8;

    return (
      <div className="all-comments-tab">
        <div className="all-commetn-count-info">
          {intl.get(
            {
              id: 'code-assets.components.comment.ATotalOfConversationslengthComments',
              defaultMessage:
                '共 {conversationsLength} 条评论，其中 {openConversationsLength} 条待解决',
            },
            {
              conversationsLength: conversations.length,
              openConversationsLength: openConversations.length,
            },
          )}
        </div>
        <div className="all-comment-list" ref={this.allCommentList}>
          {!curConversations.length && filterEmptyEle}
          {curConversations.map((conversation) => (
            <Conversation
              conversation={conversation}
              useInLog
              // line={line}
              side={conversation[0] && conversation[0].side === 'left' ? 'left' : 'right'}
              // newpath={newPath}
              issueId={(conversation[0] && conversation[0].issue && conversation[0].issue.id) || ''}
              {...this.props}
            />
          ))}
        </div>
      </div>
    );
  };

  renderTabBody = () => {
    const { allComments } = this.props;
    // const commentsAndDrafts = [...allComments, ...drafts];
    // 评论不显示草稿
    const commentsAndDrafts = [...allComments];

    return !commentsAndDrafts.length ? (
      <div className="comment-list-empty">
        <ListEmpty
          image="none"
          content={intl.get({
            id: 'code-assets.components.comment.NoComment',
            defaultMessage: '暂无评论',
          })}
          description={intl.get({
            id: 'code-assets.components.comment.PositiveCommentsToMakeReviews',
            defaultMessage: '积极评论，让评审更加高效',
          })}
          size="small"
          type="card"
          className="no-btns"
        />
      </div>
    ) : (
      this.renderAllComments()
    );
  };

  renderTitle = () => {
    const { allComments } = this.props;
    const { status } = this.state;
    if (!allComments.length) {
      return (
        <span>
          {intl.get({ id: 'code-assets.components.comment.Comments', defaultMessage: '评论' })}
        </span>
      );
    }
    return (
      <Select
        value={status}
        onChange={(value) => {
          this.setState({
            status: value,
          });

          // track({
          //   action: 'mr_activity_filter',
          //   page: 'Repo-MR',
          //   type: '',
          //   mr_id: codeReviewDetail.id,
          //   filter: value === 'all' ? 'all' : 'operation_history',
          // });
        }}
        className="comment-pannel-title-select"
        hasBorder={false}
        popupProps={{
          align: 'tl bl',
        }}
      >
        {discussStatuses.map((item) => {
          return (
            <Select.Option value={item.value} key={item.value}>
              {item.label}
            </Select.Option>
          );
        })}
      </Select>
    );
  };

  render() {
    const { isShowComment, allComments, mrCommentConfig, codeReviewDetail } = this.props;
    const allowComments = utils.allowComments(allComments.length, mrCommentConfig);
    const hasPermission = pathResource.isArchive === 'false' && allowComments;
    const { isShowWholeCommentMd } = this.state;
    if (!isShowComment || !allComments) {
      return null;
    }
    return (
      <React.Fragment>
        <div className="comment-list-container">
          <div className="comment-list-container-top">
            <div className="comment-list-container-top-title">
              {this.renderTitle()}
              <span className="comment-list-container-top-title-close">
                <ButtonIcon
                  name="false-line"
                  onClick={() => {
                    this.props.updateData({
                      isShowComment: false,
                    });
                  }}
                />
              </span>
            </div>
            {this.renderTabBody()}
          </div>
          <div
            className={`comment-bottom-wrapper height-transition ${
              isShowWholeCommentMd ? 'h190' : 'h61'
            }`}
          >
            <div
              className={`text cursor ${!hasPermission ? 'not-allow' : ''}`}
              onClick={this.showAllCommentArea}
              style={{ display: isShowWholeCommentMd ? 'none' : 'block' }}
            >
              {hasPermission ? (
                <span>
                  {intl.get({
                    id: 'code-assets.components.comment.PleaseEnterTheOverallComment',
                    defaultMessage: '请输入整体评论， @提及他人',
                  })}
                </span>
              ) : (
                <React.Fragment>
                  {allowComments
                    ? intl.get({
                        id: 'code-assets.components.comment.TheCodeLibraryHasBeen',
                        defaultMessage: '代码库已归档，不支持评论',
                      })
                    : intl.get({
                        id: 'code-assets.components.comment.HasReachedNumberOfComments',
                        defaultMessage: '已达评论数限制',
                      })}
                </React.Fragment>
              )}
            </div>
            {isShowWholeCommentMd ? (
              <div className="md">
                {/* 整体评论的md编辑器,没有保存草稿 */}
                <MdEditor
                  initValue={''}
                  useInLog
                  placeholder={intl.get({
                    id: 'code-assets.components.comment.EnterAComment',
                    defaultMessage: '请输入评论',
                  })}
                  help={intl.get(
                    {
                      id: 'code-assets.components.comment.CtrltxtShiftEnterPublishDirectly',
                      defaultMessage: '{ctrlTxt} + Shift + Enter 直接发布',
                    },
                    { ctrlTxt },
                  )}
                  onSubmitImmediate={this.onSubmitWhole} // onSubmit={this.onSubmitWhole}
                  onCancel={() => {
                    this.setState({
                      isShowWholeCommentMd: false,
                    });

                    track({
                      action: 'view_comments_panel_overall_cancel',
                      page: 'Repo-MR-changes',
                      type: '',
                      mr_id: codeReviewDetail.id,
                    });
                  }}
                  // 在面板中被底部的用户支持遮挡按钮改为左侧
                  btnAlign="left"
                  // submitBtnText={'保存为草稿'}
                  ref={(ref) => {
                    this.mdRef = ref;
                  }}
                />
              </div>
            ) : null}
          </div>
        </div>
      </React.Fragment>
    );
  }
}
